import config from '@/config'

export function downBase64(base64) {
	// 微信小程序
	if (config.isVxProgram) {
		return saveBaseImgFile(base64)
	}
	if (config.isH5 || config.isWxBrowser) {
		return downloadImageH5(base64)
	}
}

export function saveBaseImgFile(base64) {
	// 获取用户的当前设置
	uni.getSetting({
		success: res => {
			if (res.authSetting['scope.writePhotosAlbum']) { //验证用户是否授权可以访问相册
				saveImageToPhotosAlbum(base64)
				return
			}
			//重新发起获取授权
			uni.authorize({
				scope: 'scope.writePhotosAlbum',
				success: () => {
					saveImageToPhotosAlbum(base64)
				},
				fail: () => {
					uni.showToast({
						title: '请打开保存相册权限，再点击保存相册分享',
						icon: 'none',
						duration: 2000
					})
					let timer = setTimeout(() => {
						clearTimeout(timer)
						// 调起客户端小程序设置界面,让用户开启访问相册
						uni.openSetting({
							success: e => {}
						})
					}, 2000)
				}
			})
		}
	})
}


function saveImageToPhotosAlbum(base64) {
	// base64编码
	var imgSrc = base64
	var number = Math.random()
	wx.getFileSystemManager().writeFile({
		filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
		data: imgSrc,
		encoding: 'base64',
		success: res => {
			console.log('写入文件成功', res)
			wx.saveImageToPhotosAlbum({
				filePath: wx.env.USER_DATA_PATH + '/pic' + number + '.png',
				success: function(res) {
					wx.showToast({
						title: '保存成功',
					})
				},
				fail: function(err) {
					console.log('保存失败', err)
				}
			})
		},
		fail: err => {
			console.log('写入文件失败', err)
		}
	})
}

export function downImageByUrl(url,fileName) {
	if (config.isH5) {
		return downloadImageH5(url,fileName)
	} else {
		return downloadHttpImageToAlbum(url)
	}
}

export function downloadImageH5ByBase64(base64, downName) {
	if (!base64.startsWith('data:image')) {
		base64 = `data:image/png;base64,${base64}`;
	}
	
	const link = document.createElement('a');
	link.href = base64;
	link.download = downName; // 设置下载的文件名
	document.body.appendChild(link);
	link.click();
	document.body.removeChild(link);
}


function getFileExtensionFromUrl(url) {
    const extension = url.split('.').pop().toLowerCase();
    switch (extension) {
        case 'jpg':
		return 'jpg';
        case 'jpeg':
            return 'jpg';
        case 'png':
            return 'png';
        case 'gif':
            return 'gif';
        default:
            return 'png';
    }
}

export function downloadIamgeH5ByUrl(src, imgName) {
	// let image = new Image()
	// image.src = src
	// image.setAttribute("crossOrigin", "anonymous")
	// const ext = getFileExtensionFromUrl(imgName)
	// image.onload = function() {
	// 	let c = document.createElement("canvas")
	// 	c.width = image.width 
	// 	c.height = image.height 
	// 	c.getContext("2d").drawImage(image, 0, 0, image.width, image.height)
	// 	let a = document.createElement("a") 
	// 	a.download = imgName
	// 	a.href = c.toDataURL("image/" + ext) 
	// 	a.click()
	// }
	// window.location.href = src;
	window.open(src,'_blank')
}

export function downloadImageH5(source, downName) {
	if (!downName || downName.trim() === '') {
		downName = 'image_' + new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19) + '.png';
	}
	if (source.startsWith('http')) {
		downloadIamgeH5ByUrl(source, downName)
	} else {
		downloadImageH5ByBase64(source, downName)
	}
}

function downloadHttpImageToAlbum(url) {
	return new Promise((resolve, reject) => {
		wx.getImageInfo({
			src: url,
			success: function(res) {
				wx.saveImageToPhotosAlbum({
					filePath: res.path,
					success: function(res) {
						wx.showToast({
							title: '保存成功',
						})
						resolve(true)
					},
					fail: function(err) {
						console.log('保存失败', err)
						reject(err)
					}
				})
			},
			fail: function(err) {
				console.log('获取图片信息失败', err)
				reject(err)
			}
		});
	})
}